// @ts-ignore
import {createRenderer} from "../runtime-core";

export function createElement(type) {
    return document.createElement(type);
}

export function patchProps(el, key, prevVal, nextVal) {
    console.log(typeof nextVal)
    // 如果属性是以on开头，并且第三个字母是大写，那么就判断这个是一个事件属性
    const isOn = (key: string) => /^on[A-Z]/.test(key);
    if (isOn(key)) {
        const event = key.slice(2).toLowerCase();
        el.addEventListener(event, nextVal)
    } else {
        // 如果本次更新的值时undefined或者null, 那么就在el中删掉这个属性
        if (nextVal === undefined || nextVal === null) {
            el.removeAttribute(key)
        } else {
            el.setAttribute(key, nextVal);
        }

    }
}


export function insert(child, parent, anchor) {
    // parent.append(el);
    // insertBefore的作用是如果第二个参数不为null那么就把child添加到第二个参数之前，
    // 如果第二个参数是null,那么就把child做为parent的最后一个子元素添加进去
    parent.insertBefore(child, anchor || null);
}

export function remove(children) {
//      找到自己元素的父节点,在父节点中把自己删除
    const parentNode = children.parentNode;
    if (parentNode) {
        parentNode.removeChild(children);
    }
}

// hostSetElementText(container, c2)
export function setElementText(container, children) {
    container.textContent = children;
}

const render: any = createRenderer({
    createElement,
    patchProps,
    insert,
    remove,
    setElementText,

})

export function createApp(...args) {
    return render.createApp(...args);
}

export * from '../runtime-core'